//
//  DiagnoseController.m
//  EcmDoctor
//
//  Created by 张进 on 15/5/29.
//  Copyright (c) 2015年 张进. All rights reserved.
//

#import "DiagnoseController.h"
#import "QuestionDetailController.h"
#import "DetailView.h"
#import "DoctorFreeInfo.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "AppUtils.h"
#import "NetWorkUtil.h"
#import <UIImageView+AFNetworking.h>
#import <SSKeychain/SSKeychain.h>
#import "AppDelegate.h"
#import "badgeUrl.h"

@interface DiagnoseController (){
    NSMutableArray *freeData;//用于装需要展示的数据
    PagedFlowView *pageFlowView;
}

@end

@implementation DiagnoseController

//@synthesize imageArray;
//@synthesize pageFlowView;

float sWidth = 0;
float sHeight = 0;

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
//    [self refresh];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.titleView=[AppUtils generateNavigationItemTitleViewWithTitle:@"义诊"];
    
    [self upDateBadgemethod:@"getfreeinfoNum"];
    
    [self refresh];
    
}

- (void)upDateBadgemethod:(NSString *)method{
    NSString *docId = [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY];
    [badgeUrl badgeWithdoctor_info_id:docId moduleName:@"DoctorRS" methodname:method success:^(NSString *badgeNumber) {
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        
            app.diagnoseBadge.text = badgeNumber;
            if ([badgeNumber isEqualToString:@"0"]) {
                app.diagnoseBadge.alpha = 0;
            }
        
    } failure:^(NSError *error) {
        
    }];
}


- (void)refresh {
    
    freeData  = [[NSMutableArray alloc] initWithCapacity:0];
    
    double appWidth = [UIScreen mainScreen].applicationFrame.size.width;
    double appHeight = [UIScreen mainScreen].applicationFrame.size.height;
    
    
    NSLog(@"height:%f,width:%f",self.view.frame.size.height,self.view.frame.size.width);
    sWidth = self.view.frame.size.width;
    sHeight = self.view.frame.size.height;
    
    NSString *doctorId = [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY];
    
    //加载数据
    [DoctorFreeInfo getFreeInfosByDoctorId:doctorId success:^(NSArray *objs) {
        
        if (objs && objs.count > 0) {
            
            for (DoctorFreeInfo *info in objs) {
                [freeData addObject:info];
            }
            
            pageFlowView = [[PagedFlowView alloc] initWithFrame:CGRectMake(0, -self.navigationController.navigationBar.frame.size.height-self.tabBarController.navigationController.navigationBar.frame.origin.y, appWidth, appHeight)];
            pageFlowView.delegate = self;
            pageFlowView.dataSource = self;
            pageFlowView.minimumPageAlpha = 0.3;
            pageFlowView.minimumPageScale = 0.9;
            [self.view addSubview:pageFlowView];
            [pageFlowView reloadData];
            NSLog(@"cards had displayed....");
        }else{
            //若无数据默认显示什么呢？
            NSLog(@"no data to display....");
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if([segue.identifier isEqualToString:@"toDetail"]) //"toDetail"是SEGUE连线的标识
    {
        //传值
        DoctorFreeInfo *info = [freeData objectAtIndex:pageFlowView.currentPageIndex];
        QuestionDetailController *theSegue = segue.destinationViewController;
        
//        id theSegue = segue.destinationViewController;
        [theSegue setValue:info.name forKey:@"name"];
        [theSegue setValue:info.sex forKey:@"sex"];
        [theSegue setValue:[NSString stringWithFormat:@"%d", info.age] forKey:@"age"];
        [theSegue setValue:info.picUrl forKey:@"picUrls"];
        [theSegue setValue:info.voiceUrl forKey:@"voiceUrl"];
        [theSegue setValue:info.icon_Url forKey:@"headIconUrl"];
        [theSegue setValue:info.content forKey:@"bqDesc"];
        [theSegue setValue:[SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY] forKey:@"doctorId"];
        [theSegue setValue:info.ask_info_id forKey:@"askId"];
        [theSegue setValue:info.user_info_id forKey:@"user_info_id"];
        theSegue.i = 1;
        
    }
}

- (void)flowView:(PagedFlowView *)flowView didTapPageAtIndex:(NSInteger)index{
    
    DetailView *dView =(DetailView *)[flowView viewWithTag:index+400];
    DoctorFreeInfo *info = [freeData objectAtIndex:index];
    
    if ([info.info_state isEqualToString:@"0"]) {
        info.info_state=@"1";
        [freeData replaceObjectAtIndex:index withObject:info];
        //更新badge
        [badgeUrl updateOnLineStateWithmethodname:@"updateRelation" andask_info_id:info.ask_info_id success:^(BOOL bl) {
            NSLog(@"success");
            [self upDateBadgemethod:@"getfreeinfoNum"];//更新badge
        } failure:^(NSError *error) {
            
        }];
    }
    
    dView.bzView.alpha=0;
    [self performSegueWithIdentifier:@"toDetail" sender:self];
}

-(CGSize)sizeForPageInFlowView:(PagedFlowView *)flowView{
    return CGSizeMake(sWidth-60, sHeight-200);
}
-(NSInteger)numberOfPagesInFlowView:(PagedFlowView *)flowView{
    return [freeData count];
}
-(UIView *)flowView:(PagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    
    DoctorFreeInfo *info = [freeData objectAtIndex:index];
    DetailView *dView = [DetailView instanceDetailView];
    dView.layer.cornerRadius=5;
    dView.tag=index+400;
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[NetWorkUtil getImagesBaseUrl],info.icon_Url];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    [dView.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"icon"]];
    
//    [dView.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"icon"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        
////        CGSize size = image.size;
////        CGFloat startX = 0;
////        CGFloat startY = 0;
////        //        if (size.width >= size.height) {
////        //            startY = (size.width - size.height)/2.0;
////        //            image = [AppUtils getSubImage:image withRect:CGRectMake(startX, startY, size.height, size.height)];
////        //        }else{
////        //            startX = (size.height - size.width)/2.0;
////        //            image = [AppUtils getSubImage:image withRect:CGRectMake(startX, startY, size.width, size.width)];
////        //        }
////        image = [AppUtils getSubImage:image withRect:CGRectMake(startX, startY, size.width, size.width)];
////        dView.imageView.image = image;
////        
////        NSLog(@"complete");
//    }];
    dView.bzView.backgroundColor = [UIColor redColor];
//    [dView bringSubviewToFront:dView.bzView];
    
    if([info.info_state isEqualToString:@"1"])
    {
        dView.bzView.alpha=0;
    }
    else
    {
        dView.bzView.alpha=1;
    }
    
    dView.leftBottomDate.text = info.infodate;
    if (info.picUrl) {
        dView.rightBottomPicNum.text = [NSString stringWithFormat:@"%d",(int)info.picUrl.count];
    }else{
        dView.rightBottomPicNum.text = @"0";
    }
    dView.middleDesc.text = info.content;
    dView.name.text = info.name;
    dView.sex.text = info.sex;
    //dView.age.text = info.age;
   //  dView.age.text = [NSString stringWithFormat:@"%d",info.age.intValue];
    if (info.voiceUrl && info.voiceUrl.length > 0) {
        dView.rightBottomVoiceNum.text = @"1";
    }else{
        dView.rightBottomVoiceNum.text = @"0";
    }
    
    dView.dWidth = sWidth-60;
    dView.dHeight = sHeight-200;
    
    return dView;
    
}

//-(UIImage*)  OriginImage:(UIImage *)image   scaleToSize:(CGSize)size
//{
//    // 创建一个bitmap的context
//    // 并把它设置成为当前正在使用的context
//    UIGraphicsBeginImageContext(size);
//
//    // 绘制改变大小的图片
//    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
//
//    // 从当前context中创建一个改变大小后的图片
//    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
//
//    // 使当前的context出堆栈
//    UIGraphicsEndImageContext();
//
//    // 返回新的改变大小后的图片
//    return scaledImage;
//}

//- (UIViewController *)findViewController:(UIView *)sourceView
//{
//    id target=sourceView;
//    while (target) {
//        target = ((UIResponder *)target).nextResponder;
//        if ([target isKindOfClass:[UIViewController class]]) {
//            break;
//        }
//    }
//    return target;
//}

@end
